﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OfficeOpenXml;
using static simu485.Views.C485SrvCmd;

namespace simu485.Data
{
    public class C485Excel
    {

        public static bool Save(string file_path, List<C485CmdItem> cmds)
        {
            ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
            // 创建一个Excel文件
            using (ExcelPackage package = new ExcelPackage())
            {
                // 添加一个工作表
                ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("Sheet1");
                worksheet.Cells[1, 1].Value = "指令码";
                worksheet.Cells[1, 2].Value = "指令描述";
                worksheet.Cells[1, 3].Value = "指令值";
                worksheet.Cells[1, 4].Value = "发送数据";
                worksheet.Cells[1, 5].Value = "接收数据";
                worksheet.Column(1).Width = 15;
                worksheet.Column(2).Width = 40;
                worksheet.Column(3).Width = 20;
                worksheet.Column(4).Width = 50;
                worksheet.Column(5).Width = 50;
                for (int i = 0; i < cmds.Count; i++)
                {
                    worksheet.Cells[i + 2, 1].Value = cmds[i].cmd_code.ToString("X04");
                    worksheet.Cells[i + 2, 2].Value = cmds[i].des;
                    worksheet.Cells[i + 2, 3].Value = cmds[i].value;
                    worksheet.Cells[i + 2, 4].Value = cmds[i].send;
                    worksheet.Cells[i + 2, 5].Value = cmds[i].recv;
                }
                // 向工作表中写入数据

                // 保存Excel文件到本地
                FileInfo fileInfo = new FileInfo(file_path);
                package.SaveAs(fileInfo);
            }

            return true;
        }

        public static List<C485CmdItem>? Load(string file_path)
        {
            if (!File.Exists(file_path)) return null;
            List<C485CmdItem> cmds = new List<C485CmdItem>();

            ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
            // 读取Excel文件
            using (ExcelPackage package = new ExcelPackage(new FileInfo(file_path)))
            {
                // 获取第一个工作表
                ExcelWorksheet worksheet = package.Workbook.Worksheets[0];

                // 从工作表中读取数据
                for (int i = worksheet.Dimension.Start.Row+1; i <= worksheet.Dimension.End.Row; i++)
                {
                    C485CmdItem item = new C485CmdItem();
                    item.cmd_code = ushort.Parse(worksheet.Cells[i, 1].Text, System.Globalization.NumberStyles.HexNumber);
                    item.des = worksheet.Cells[i, 2].Text;
                    item.value = worksheet.Cells[i, 3].Text;
                    item.send = worksheet.Cells[i, 4].Text;
                    item.recv = worksheet.Cells[i, 5].Text;
                    cmds.Add(item);
                }
            }
            return cmds;
        }
    }
}
